/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.trandio.manager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.trandio.dao.ContratoDAO;
import org.trandio.dao.ContratoInterface;
import org.trandio.model.ActividadContratadaVO;
import org.trandio.model.ActividadVO;
import org.trandio.model.ContratoVO;
import org.trandio.model.GrupoActividadVO;

/**
 *
 * @author root
 */
public class ContratoServlet extends HttpServlet {

    ActividadContratadaVO actividadContratadaVO;
    private List<ActividadContratadaVO> listContratado;
    private List<ActividadVO> listHabilitada;
    ContratoInterface contratoInterface;
    private List<GrupoActividadVO> listgrActividadVO;
    private ContratoVO contratoVO;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();



        String idCto = request.getParameter("id");




        switch (Integer.parseInt(request.getParameter("tipo"))) {
            case 1:
                String codh = request.getParameter("buscarCodh");
                String grupoAct = request.getParameter("id_grupo_actividad");
                contratoInterface = new ContratoDAO();
                try {
                    listHabilitada = contratoInterface.consultarActividadesHabilitadas(codh, Integer.parseInt(grupoAct), Integer.parseInt(idCto));
                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }


                Iterator it = listHabilitada.iterator();


                out.println("<table width='100%' style='border:1px solid gray;font-size:12px'  class='ui-widget-content' cellspacing='0'>");
                //out.println("<tr class='ui-widget-header'><td colspan='4'>Actividades Habilitadas</td></tr>");
                while (it.hasNext()) {
                    ActividadVO b = (ActividadVO) it.next();

                    out.println("<tr  class='ui-state-hover'><td><input type='checkbox' class='check_me' value='" + b.getId() + "' id='codact' onclick='/*seleccionarActividad(" + b.getId() + ",&quot;" + b.getCodigo() + "&quot; ,&quot;" + b.getDescripcion() + "&quot;,&quot;" + b.getGrupo_funcional() + "&quot;)*/'/></td>");
                    out.println("<td>" + b.getCodigo() + "</td><td><input size='30' title='" + b.getDescripcion() + "' class='ui-widget-content' readonly='true' type='text' value='" + b.getDescripcion() + "'/></td><td>" + b.getDescmanual() + "</td>");
                    //out.println("<td>"+b.getCodigo()+"</td><td>"+b.getDescripcion()+"</td><td>"+b.getDescmanual()+"</td>");
                }
                out.println("</table>");

                break;

            case 2:

                if (idCto.equals("")) {
                    idCto = "0";
                }

                contratoInterface = new ContratoDAO();
                try {

                    int first = Integer.parseInt(request.getParameter("offset"));
                    int limit = Integer.parseInt(request.getParameter("limit"));
                    String codigo = request.getParameter("codact");

                    String grupo = "0";

                    if (!request.getParameter("id_grupo_actividad").equals("null")) {
                        grupo = request.getParameter("id_grupo_actividad");
                    }



                    listContratado = contratoInterface.consultarActividadesContratadas(Integer.parseInt(idCto), first, limit, codigo, Integer.parseInt(grupo));

                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }


                Iterator itcton = listContratado.iterator();


                out.println("<table width='100%' style='border:1px solid gray;font-size:12px' class='ui-widget-content' cellspacing='0'>");
                //out.println("<tr class='ui-widget-header'><td colspan='3'>Actividades Habilitadas</td></tr>");
                while (itcton.hasNext()) {
                    ActividadContratadaVO b = (ActividadContratadaVO) itcton.next();

                    //out.println("<tr><td><input type='radio' id='codact' onclick='seleccionarActividad("+b.getId()+",&quot;"+b.getCodigo()+"&quot; ,&quot;"+b.getDescripcion()+"&quot;,&quot;"+b.getGrupo_funcional()+"&quot;)'/></td>");
                    out.println("<tr  class='ui-state-hover'><td>" + b.getCodigo()
                            + "</td><td><input size='30' title='" + b.getActividad()
                            + "' class='ui-widget-content'readonly='true' type='text' value='" + b.getActividad()
                            + "'/></td><td>" + b.getValor() + "</td><td><img width='12px' heigth='12px' style='cursor:pointer' onclick='descontratarActividad(" + b.getId() + ")' src='../common/img/del.png' /></td></tr>");
                }
                out.println("</table>");

                break;


            case 3:
                contratoInterface = new ContratoDAO();
                int grupoActCon = Integer.parseInt(request.getParameter("id_grupo_actividad"));
                try {
                    listHabilitada = contratoInterface.consultarActividadesHabilitadas("", grupoActCon, Integer.parseInt(idCto));
                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (grupoActCon > 0) {
                    for (ActividadVO actvo : listHabilitada) {
                        System.out.println("Grupo Actividad: " + actvo.getId());
                        System.out.println("ID Contrato: " + idCto);
                        try {
                            contratoInterface.contratarActividad(Integer.parseInt(idCto), actvo.getId());
                        } catch (SQLException ex) {
                            Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (NamingException ex) {
                            Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                }
                break;


            case 4:
                contratoInterface = new ContratoDAO();
                String[] dato = request.getParameter("ids").split(",");

                for (int i = 0; i < dato.length; i++) {
                    try {
                        contratoInterface.contratarActividad(Integer.parseInt(idCto), Integer.parseInt(dato[i]));
                    } catch (SQLException ex) {
                        Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NamingException ex) {
                        Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                break;


            case 5:
                contratoInterface = new ContratoDAO();
                int idActividadContrato = Integer.parseInt(request.getParameter("idCtoAct"));
                int idContrato = Integer.parseInt(idCto);

                try {
                    contratoInterface.descontratarActividad(idContrato, idActividadContrato);
                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }


                break;


            case 6:
                contratoInterface = new ContratoDAO();

                if (idCto.equals("")) {
                    idCto = "0";
                }

                int idCon = Integer.parseInt(idCto);

                int contratadas;
                try {
                    contratadas = contratoInterface.contarContratadas(idCon);
                    out.println(contratadas);
                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }

                break;



            case 7:
                contratoInterface = new ContratoDAO();
                try {


                    listgrActividadVO = contratoInterface.consultarGrupoContratado(Integer.parseInt(idCto));

                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }


                Iterator grucon = listgrActividadVO.iterator();


                out.println("<table width='100%' style='border:1px solid gray' class='extdt-caption'>");
                out.println("<tr class='ui-widget-header'><td colspan='4'>Grupos Contratados X Descuentos</td></tr>");
                out.println("<tr class='ui-widget-header'><td>Codigo</td><td>Descripcion</td><td>Asignar Porc</td><td>Modelo Copagos</td></tr>");

                while (grucon.hasNext()) {
                    GrupoActividadVO b = (GrupoActividadVO) grucon.next();

                    //out.println("<tr><td><input type='radio' id='codact' onclick='seleccionarActividad("+b.getId()+",&quot;"+b.getCodigo()+"&quot; ,&quot;"+b.getDescripcion()+"&quot;,&quot;"+b.getGrupo_funcional()+"&quot;)'/></td>");


                    GrupoActividadVO gru = new GrupoActividadVO();
                    try {
                        gru = contratoInterface.getCopagosGrupo(b.getId(), Integer.parseInt(idCto));
                    } catch (SQLException ex) {
                        Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NamingException ex) {
                        Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }


                    out.println("<tr><td>" + b.getCodigo()
                            + "</td><td>" + b.getDescripcion()
                            + "</td><td align='center'><img style='cursor:pointer' onclick='ventanaModalCopagos(" + b.getId() + "," + idCto + ")' src='../common/img/porc.png' /></td>"
                            + "<td><table width='100%'>"
                            + "<tr style='background-color: #72B42D'>"
                            + "<td align='center'>Codigo</td>"
                            + "<td align='center'>Nivel 0</td>"
                            + "<td align='center'>Nivel 1</td>"
                            + "<td align='center'>Nivel 2</td>"
                            + "<td align='center'>Nivel 3</td>"
                            + "<td align='center'>Nivel 3</td>"
                            + "</tr><tr style='background-color: #C0C0C0'>"
                            + "<td align='center'>" + gru.getIdcopago() + "</td>"
                            + "<td align='center'>" + gru.getDn0() + "%</td>"
                            + "<td align='center'>" + gru.getDn1() + "%</td>"
                            + "<td align='center'>" + gru.getDn2() + "%</td>"
                            + "<td align='center'>" + gru.getDn3() + "%</td>"
                            + "<td align='center'>" + gru.getDn4() + "%</td>"
                            + "</tr></table></td></tr>");

                }
                out.println("</table>");

                break;


            case 8:

                try {
                    listgrActividadVO = contratoInterface.consultarGrupoContratado(Integer.parseInt(idCto));
                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }


                Iterator gactc = listgrActividadVO.iterator();
                out.println("<option value='0'>:: Seleccione ::</option>");
                while (gactc.hasNext()) {
                    GrupoActividadVO m = (GrupoActividadVO) gactc.next();
                    out.println("<option value='" + m.getId() + "'>" + m.getDescripcion() + "</option>");
                }
                break;


            case 9:

                contratoInterface = new ContratoDAO();
                int idGrupo = Integer.parseInt(request.getParameter("idGrupoAct"));
                int idCont = Integer.parseInt(request.getParameter("id"));

                try {
                    contratoInterface.descontratarGrupo(idCont, idGrupo);
                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }

                break;

            case 10:

                contratoInterface = new ContratoDAO();

                int idContr = 0;

                if (!request.getParameter("id_Contrato").equals("")) {
                    idContr = Integer.parseInt(request.getParameter("id_Contrato").trim());
                }

                //Integer.parseInt(request.getParameter("id_Contrato").trim());

                try {
                    contratoVO = contratoInterface.getContratoPyp(idContr);
                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }

                Gson gson = new  GsonBuilder().serializeNulls().create();
                out.println(gson.toJson(contratoVO));

                break;


            case 11:

                contratoInterface = new ContratoDAO();

                int idc = 0;

                if (!request.getParameter("idcontrato").equals("")) {
                    idc = Integer.parseInt(request.getParameter("idcontrato").trim());
                }


                try {
                    contratoVO = contratoInterface.getContrato(idc);
                } catch (SQLException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NamingException ex) {
                    Logger.getLogger(ContratoServlet.class.getName()).log(Level.SEVERE, null, ex);
                }

                Gson gsonCon = new GsonBuilder().serializeNulls().create();
                out.println(gsonCon.toJson(contratoVO));

                break;






        }

        try {
            /*
             * TODO output your page here out.println("<html>");
             * out.println("<head>"); out.println("<title>Servlet
             * ContratoServlet</title>"); out.println("</head>");
             * out.println("<body>"); out.println("<h1>Servlet ContratoServlet
             * at " + request.getContextPath () + "</h1>");
             * out.println("</body>"); out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
